<template>

  <ContentWrap>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">基础信息</div>
      </div>
      <el-form 
        ref="formRef" 
        :inline="true" 
        :model="formData.data" 
        :rules="formRules"
        class="-mb-15px"
        label-width="auto"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.data.name" class="!w-270px" clearable placeholder="姓名"/>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input maxlength="18" v-model="formData.data.idCard" class="!w-270px" clearable placeholder="请输入身份证号"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select 
            v-model="formData.data.gender" 
            class="!w-270px" 
            clearable
            placeholder="请选择性别"
          >
            <el-option
              v-for="item in genderList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            v-model="formData.data.birthDate"
            class="!w-270px"
            type="date"
            placeholder="请选择出生日期"
            @change="e => formData.data.birthDate = formatDateToYMD(e)"
          />
        </el-form-item>

        <el-form-item label="民族" prop="ethnic">
          <el-select 
            v-model="formData.data.ethnic" 
            class="!w-270px" 
            clearable 
            filterable
            placeholder="请选择民族"
          >
            <el-option
              v-for="item in ethnicList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="籍贯" prop="nativePlace">
          <el-input v-model="formData.data.nativePlace" class="!w-270px" clearable placeholder="请输入籍贯"/>
        </el-form-item>
        <el-form-item label="政治面貌" prop="politicalStatus">
          <el-select 
            v-model="formData.data.politicalStatus" 
            class="!w-270px" 
            clearable
            placeholder="请选择政治面貌"
          >
            <el-option
              v-for="item in politicalList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="婚姻状况" prop="maritalStatus">
          <el-select 
            v-model="formData.data.maritalStatus" 
            class="!w-270px" 
            clearable
            placeholder="请选择婚姻状况"
          >
            <el-option
              v-for="item in maritalList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学历" prop="education">
          <el-select 
            v-model="formData.data.education" 
            class="!w-270px" 
            clearable
            placeholder="请选择学历"
          >
            <el-option
              v-for="item in degreeList" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input maxlength="11" v-model="formData.data.phone" class="!w-270px" clearable placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input v-model="formData.data.emergencyContact" class="!w-270px" clearable placeholder="请输入紧急联系人"/>
        </el-form-item>
        <el-form-item label="紧急联系电话" prop="urgentPhone">
          <el-input maxlength="11" v-model="formData.data.urgentPhone" class="!w-270px" clearable placeholder="请输入紧急联系电话"/>
        </el-form-item>

        <el-form-item label="身体状况" prop="healthStatus">
          <el-select 
            v-model="formData.data.healthStatus" 
            class="!w-270px" 
            clearable
            placeholder="请选择身体状况"
          >
            <el-option
              v-for="item in physicalList" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankCard">
          <el-input v-model="formData.data.bankCard" class="!w-270px" clearable placeholder="请输入银行卡号"/>
        </el-form-item>
        <el-form-item label="入职时间" prop="entryTime">
          <el-date-picker
            v-model="formData.data.entryTime"
            class="!w-270px"
            type="date"
            placeholder="请选择入职时间"
            @change="e => formData.data.entryTime = formatDateToYMD(e)"
          />
        </el-form-item>
        <!-- <el-form-item label="签约时间" prop="contractYear">
          <el-date-picker
            class="!w-270px"
            v-model="formData.data.contractYear"
            format-value="yyyy"
            type="year"
            placeholder="请选择签约年份"
            @change="e => formData.data.contractYear = formatToYear(e)"
          />
        </el-form-item> -->
        
      </el-form>
    </div>
  </ContentWrap>

  <ContentWrap>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">证照附件信息</div>
      </div>

      <div class="flex-s">
        <div class="upload_box flex-c">
          <el-upload
            class="avatar_uploader flex-c"
            :http-request="e => customRequest(e, 'idCardFront')"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.data.idCardFront" :src="formData.data.idCardFront" class="avatar" />
            <el-icon v-else class="avatar_uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="uploader__text">身份证人像面</div>
        </div>

        <div class="upload_box flex-c">
          <el-upload
            class="avatar_uploader flex-c"
            :http-request="e => customRequest(e, 'idCardBack')"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.data.idCardBack" :src="formData.data.idCardBack" class="avatar" />
            <el-icon v-else class="avatar_uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="uploader__text">身份证国徽面</div>
        </div>

        <div class="upload_box flex-c">
          <el-upload
            class="avatar_uploader flex-c"
            :http-request="e => customRequest(e, 'bankCardPhoto')"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.data.bankCardPhoto" :src="formData.data.bankCardPhoto" class="avatar" />
            <el-icon v-else class="avatar_uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="uploader__text">银行卡照片</div>
        </div>

        <div class="upload_box flex-c mx-60">
          <el-upload
            class="avatar_uploader cun flex-c"
            :http-request="e => customRequest(e, 'photo')"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.data.photo" :src="formData.data.photo" class="avatar" />
            <el-icon v-else class="avatar_uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="uploader__text">寸照</div>
        </div>


        <div class="upload_box !w-400px">
          <UploadFile
            v-model="formData.data.attachment"
            class="upload-demo"
            :http-request="e => customRequest(e, 'attachment')"
            :fileSize="20"
            :fileType="['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']"
            :limit="10"
          />
        
        
        </div>
      </div>

    </div>
  </ContentWrap>

  <ContentWrap>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">技能信息</div>
      </div>

      <el-table :data="formData.data.skills">
        <el-table-column align="center" label="工种类型" prop="jobType">
          <template #default="scope">
            <el-select 
              v-if="scope.row.editable" 
              v-model="scope.row.jobType" 
              filterable
              clearable
              placeholder="请选择"
              @change="e => jobTypeChange(e, scope.$index)"
            >
              <el-option
                v-for="item in jobTypeList"
                :key="item.value"
                :disabled="item.disabled"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
            <div v-else>{{ scope.row.jobType }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="技能证书" prop="skillCertificate">
          <template #default="scope">
            <el-select 
              v-if="scope.row.editable" 
              v-model="scope.row.skillCertificate" 
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in jobTypeList2"
                :key="item.value"
                :disabled="item.disabled" 
                @change="e => jobTypeChange2(e, scope.$index)"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
            <div v-else>{{ scope.row.skillCertificate }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="证书附件" prop="certificateAttachment">
          <template #default="scope">
            <div v-if="scope.row.editable">
              <div class="flex-s" v-if="scope.row.certificateAttachment">
                <span class="!w-220px ellipsis">{{ scope.row.certificateAttachment.slice(scope.row.certificateAttachment.lastIndexOf('/') + 1) }}</span>
                
                <span class="mx-12">
                  <el-upload
                      :http-request="e => requestTable(e, scope.$index)"
                      :show-file-list="false"
                      :before-upload="beforeUpload"
                    >
                      <template #trigger><a href="#">修改</a></template>
                    </el-upload>
                </span>
                <a :href="scope.row.certificateAttachment">下载</a>
              </div>
              
              <el-upload
                v-else
                :http-request="e => requestTable(e, scope.$index)"
                :show-file-list="false"
                :before-upload="beforeUpload"
              >
                <template #trigger><a href="#">上传附件</a></template>
              </el-upload>

            </div>
            <div class="flex-s" v-else>
              <div class="!w-220px ellipsis">{{ scope.row.certificateAttachment.slice(scope.row.certificateAttachment.lastIndexOf('/') + 1) }}</div>
              <a class="ml-12" :href="scope.row.certificateAttachment">下载</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="时间有效期" prop="issueDate">
          <template #default="scope">
            <el-date-picker
              style="width: 100%"
              v-if="scope.row.editable"
              v-model="scope.row.scopeDate"
              type="daterange"
              range-separator="~" 
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="e => scopeDateChange(e, scope.$index)"
            />
            <div v-else>
              <span v-if="scope.row.scopeDate && scope.row.validityPeriod">{{ scope.row.issueDate }} ~ {{ scope.row.validityPeriod }}</span>
              <span v-else>-</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :width="200" align="center" label="操作">
          <template #default="scope">

            <div v-if="scope.row.editable">
              <el-button link type="info" @click="cancle(scope.$index)">取消</el-button>
              <el-button link type="primary" @click="save(scope.row, scope.$index)">保存</el-button>
            </div>
            <div v-else>
              <el-button link type="primary" @click="edit(scope.$index)">
                编辑
              </el-button>
              <el-popconfirm
                class="box-item"
                title="确定删除？"
                placement="top-end"
                @confirm="del(scope.$index)"
              >
                <template #reference>
                  <el-button link type="danger">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
  
      </el-table>

      <el-button @click="addRow" plain class="addRow">
        <el-icon class="mr-6"><Plus /></el-icon>  添加
      </el-button>

    </div>
  </ContentWrap>

  <ContentWrap class="flex-c">
    <el-button class="!w-80px" type="primary" @click="submitForm">确定</el-button>
    <el-button class="!w-80px" type="warning" @click="closeForm">取消</el-button>
  </ContentWrap>
</template>
<script setup>
import { ref, reactive, inject } from "vue"
import { Plus } from '@element-plus/icons-vue'
import * as RoleApi from '@/api/system/role'
import { formatDateToYMD, parseYMDToDate } from '@/utils/index'
import { formatToYear } from '@/utils/formatTime'
import * as PersonnelApi from '@/api/system/personnel'
import { formRules } from './formRules'
import { updateFile } from "@/api/infra/file/index.ts"
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFile } from "@/components/UploadFile/index.ts"
import { 
  physicalList,
  jobTypeList,
  jobTypeList2,
  degreeList,
  politicalList, 
  maritalList, 
  genderList,
  ethnicList 
} from './json'
const setPageStatus = inject('setPageStatus', () => { });
let formData = reactive({
  data:{
    name: '',
    idCard: '',
    gender: '',
    phone: '',
    idCardFront: null,
    idCardBack: null,
    skills: [],
    attachment: []
  }
})

let scopeDate = ref('')
const formRef = ref(null)

let copyData = ref([])


let pageStatus = ref(1) // 1新增  2编辑
/** 初始化 **/
const init = (type, id) => {
  pageStatus.value = type
  if (id) {
    getDetails(id)
  }else{
    formData.data = {
          name: '',
          idCard: '',
          gender: '',
          userType: 1,
          phone: '',
          idCardFront: null,
          idCardBack: null,
          skills: [],
          attachment: []
    }
  }
  jobTypeList.value.forEach(item => item.disabled = false)
  jobTypeList2.value.forEach(item => item.disabled = false)
}

/** 查询详情信息 */
const getDetails = async (id) => {
  // loading.value = true
  try {
    const data = await PersonnelApi.getPersonnelDetail(id)
    data.userType = 1
    if (data.skills?.length > 0) {
      data.skills.forEach(item => {
        item.scopeDate = [item.issueDate ? parseYMDToDate(item.issueDate) : '', item.validityPeriod ? parseYMDToDate(item.validityPeriod) : '']
        item.editable = false
      })
    }else{
      data.skills = []
    }
    formData.data = data

  } finally {
    // loading.value = false
  }
}

onMounted(() => {
  
})

/**
 * 图片上传逻辑 - 开始
 */

const beforeAvatarUpload = (rawFile) => {
  let imgTypeList = ['image/jpeg', 'image/png', 'image/webp']
  if (!imgTypeList.includes(rawFile.type)) {
    ElMessage.error('请上传jpg、png、webp格式图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error('图片大小不能超过 20MB!')
    return false
  }
  return true
}

const customRequest = async (options, type) => {
  const upFilesData = new FormData()
  upFilesData.append('file', options.file)
  try {
    const res = await updateFile(upFilesData)
    if(type === 'attachment'){
      formData.data[type].push(res.data)
    }else{
      formData.data[type] = res.data
    }
  }finally {
    
  }
  
}
/**
 * 图片上传逻辑 - 结束
 */



/**
 * 技能信息逻辑处理 - 开始
*/

// 工种类型
const jobTypeChange = (e, index) => {
  formData.data.skills[index].jobType = e
  setJobTypeDisabled()
}
function setJobTypeDisabled() {
  formData.data.skills.forEach(item => {
    jobTypeList.value.forEach(curr => {
      if(curr.label === item.jobType){
        curr.disabled = true
      }
    })
  })
}


// 技能证书
const jobTypeChange2 = (e, index) => {
  formData.data.skills[index].skillCertificate = e
  setJobTypeDisabled2()
}
function setJobTypeDisabled2() {
  formData.data.skills.forEach(item => {
    jobTypeList2.value.forEach(curr => {
      if(curr.label === item.skillCertificate){
        curr.disabled = true
      }
    })
  })
}

const requestTable = async (options, index) => {
  const upFilesData = new FormData()
  upFilesData.append('file', options.file)
  try {
    const res = await updateFile(upFilesData)
    formData.data.skills[index].certificateAttachment = res.data
  }finally {
    
  }
}

// 文件上传之前判断
const beforeUpload = (file) => {
  let fileExtension = ''
  if (file.name.lastIndexOf('.') > -1) {
    fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
  }
  
  const fileType = ['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']
  const isImg = fileType.some((type) => {
    if (file.type.indexOf(type) > -1) return true
    return !!(fileExtension && fileExtension.indexOf(type) > -1)
  })
  const isLimit = file.size < 20 * 1024 * 1024
  if (!isImg) {
    ElMessage.error(`文件格式不正确, 请上传${fileType.join('/')}格式!`)
    return false
  }
  if (!isLimit) {
    ElMessage.error(`上传文件大小不能超过${20}MB!`)
    return false
  }
}

const scopeDateChange = (val, index) => {
  let skills = JSON.parse(JSON.stringify(formData.data.skills))
  skills[index].scopeDate = val
  skills[index].issueDate = formatDateToYMD(val[0])
  skills[index].validityPeriod = formatDateToYMD(val[1])
  formData.data.skills = skills
}

const addRow = () => {
  let skills = JSON.parse(JSON.stringify(formData.data.skills))
  copyData.value = JSON.parse(JSON.stringify(skills))
  let flag = skills.find(item => item.editable)
  if (flag) {
    ElMessage.warning('请先保存当前数据')
    return
  }
  skills.push({
    jobType: null, // 工种类型
    skillCertificate: null, // 技能证书
    certificateAttachment: '', // 证书附件
    issueDate: '',
    validityPeriod: '',
    editable: true,
    scopeDate: '',
  })
  formData.data.skills = skills
  setJobTypeDisabled()
  setJobTypeDisabled2()
}

const edit = (index) => {
  let skills = JSON.parse(JSON.stringify(formData.data.skills))
  let flag = skills.find(item => item.editable)
  if (flag) {
    ElMessage.warning('请先保存当前数据')
    return
  }
  copyData.value = JSON.parse(JSON.stringify(skills))
  console.log(copyData.value);
  skills[index].editable = true
  formData.data.skills = skills
}

const del = (index) => {
  let skills = JSON.parse(JSON.stringify(formData.data.skills))
  skills.splice(index, 1)
  formData.data.skills = skills
}

const cancle = () => {
  let skills = JSON.parse(JSON.stringify(copyData.value))
  formData.data.skills = skills
}

const save = (row, index) => {
  let skills = JSON.parse(JSON.stringify(formData.data.skills))

  const {jobType, skillCertificate, certificateAttachment, scopeDate} = row
  if (!jobType) {
    ElMessage.warning('请选择工种类型')
    return
  }
  if (!skillCertificate) {
    ElMessage.warning('请选择技能证书')
    return
  }
  if (!certificateAttachment) {
    ElMessage.warning('请上传证书附件')
    return
  }
  if (scopeDate.length !== 2) {
    ElMessage.warning('请选择有效期')
    return
  }
  skills.forEach(item => item.editable = false)
  formData.data.skills = skills
}
/**
 * 技能信息逻辑处理 - 结束
 */




const submitForm = async () => {
  const { skills } = formData.data
  const flag = skills.find(item => item.editable)
  if(flag){
    ElMessage.error('请先保存技能信息数据')
    return
  }
  const formEl = formRef.value
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (pageStatus.value === 1) {
        PersonnelApi.addPersonnel(formData.data).then(res => {
          setPageStatus(1)
          ElMessage.success('新增成功')
        })
      } else {
        PersonnelApi.editPersonnel(formData.data).then(res => {
          setPageStatus(1)
          ElMessage.success('编辑成功')
        })
      }
    } else {
      for(let key in fields){
        ElMessage.error(fields[key][0].message)
      }
    }
  })
}

const closeForm = () => {
  // 关闭表单弹窗逻辑
  setPageStatus(1)
}


defineExpose({
  init,
})

</script>
<style lang="scss" scoped>
.content{
    width: 100%;
    min-height: 80px;
    padding: 6px;
    // border-right: 1px solid #eee;
    box-sizing: border-box;
    .content_head {
        margin-bottom: 24px;
        .line {
            width: 5px;
            height: 21px;
            background: #50B5FF;
        }
        .title {
            font-size: 18px;
            color: #333;
            margin-left: 12px;
            font-weight: 600;
        }
    }
}

.upload_box{
  height: 170px;
  flex-direction: column;
  margin-left: 18px;
  .uploader__text{
    margin-top: 6px;
  }
}

.avatar_uploader {
  width: 260px;
  height: 100%;
  border: 1px dashed #999;
  color: #999;
  border-radius: 2px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  
  .avatar_uploader-icon {
    font-size: 28px;
    width: 260px;
    height: 170px;
    text-align: center;
  }

  img{
    width: 260px;
    height: 170px;
  }
}
.avatar_uploader:hover {
  border-color: #2568f8;
  color: #2568f8;
}


.cun{
  width: 100px;
  height: 140px;
}

.addRow{
  margin-top: 12px;
  width: 100%;
}

::v-deep .el-icon--close-tip{
  display: none !important;
}
::v-deep .el-upload-list{
  overflow-y: scroll;
  height: 105px;
}
::v-deep .fileName{
  width: 285px;
}
</style>
